MongoDB 结合 PHP

1.安装 PHP 的 MongoDB 扩展

1
[root@primary ~]# wget 'https://codeload.github.com/mongodb/mongo-php-driver/zip/master' -O /usr/local/src/mong_php.zip
1
2
3
4
[root@primary ~]# cd /usr/local/src
[root@primary src]# unzip mong_php.zip
[root@primary src]# cd mongo-php-driver-master/
[root@primary mongo-php-driver-master]# /usr/local/php/bin/phpize

        出错无法解决,重新下载包

1
2
3
4
5
6
[root@primary ~]# wget http://pecl.php.net/get/mongo-1.4.5.tgz
[root@primary ~]# tar xfv mongo-1.4.5.tgz
[root@primary ~]# cd mongo-1.4.5
[root@primary mongo-1.4.5]# /usr/local/php/bin/phpize
[root@primary mongo-1.4.5]# ./configure --with-php-config=/usr/local/php/bin/php-config
[root@primary mongo-1.4.5]# make && make install

        编辑 /usr/local/php/etc/php.ini

1
[root@primary mongo-1.4.5]# vim /usr/local/php/etc/php.ini

        增加 extension = mongo.so

1
extension = mongo.so

        /usr/local/php/bin/php –m

1
[root@primary mongo-1.4.5]# /usr/local/php/bin/php -m

        重启apache,重新加载php

2.测试 MongoDB 扩展

        编辑 /usr/local/apache2/htdocs/1.php

1
[root@primary ~]# vim /usr/local/apache2/htdocs/1.php

        增加

1
2
3
4
5
6
7
8
<?php
// 连接到mongodb
$m = new MongoClient();
echo "Connection to database successfully";
// 选择一个数据库
$db = $m->mydb;
echo "Database mydb selected";
?>

1
2
[root@primary ~]# curl localhost/1.php
Connection to database successfullyDatabase mydb selected

        参考MongoDB PHP